/**
 * Created by liubin on 2014/06/06
 * 主Controller
 */
Ext.define('Order.controller.Main', {
    // 继承 Controller类
    extend: 'Ext.app.Controller',
    // 必须引用的类
    requires: ['Ext.data.proxy.Rest', 'Ext.Img', 'Ext.field.Text', 'Ext.field.TextArea', 'Ext.field.Number',
        'Ext.field.Spinner', 'Ext.field.Hidden', 'Ext.MessageBox'],
    config: {
        // 预加载的model
        models: ['Store', 'Item', 'Cart', 'CartCheck'],
        // 预加载的store
        stores: ['Store', 'Item', 'Cart'],
        // 预加载的视图
        views: ['NavView', 'StoreView', 'ItemView', 'OrderForm', 'CartView', 'CartList', 'CartForm'],
        // 对画面控件建立引用
        refs: {
            main: 'mainview',
            nav: 'navview',
            cart: 'cartnav',
            storeList: 'storelist',
            // 需要自动创建的
            itemList: {
                selector: 'itemlist',
                xtype: 'itemlist',
                autoCreate: true
            },
            // 需要自动创建的
            orderForm: {
                selector: 'navview orderform',
                xtype: 'orderform',
                autoCreate: true
            },
            // 需要自动创建的
            cartForm: {
                selector: 'cartnav orderform',
                xtype: 'orderform',
                autoCreate: true
            },
            billForm: {
                selector: 'cartnav cartform',
                xtype: 'cartform',
                autoCreate: true
            },
            countField: 'orderform spinnerfield',
            orderSubmitBtn: 'navview button[action=submit]',
            cartList: 'cartlist',
            cartChangeBtn: 'cartnav button[action=submit]',
            cartDeleteBtn: 'cartnav button[action=delete]',
            billSubmitBtn: 'cartnav button[action=bill]'
        },
        // 事件监听器
        control: {
            main: {
                activeitemchange: 'tabChange'
            },
            nav: {
                pop: 'onNavPop',
                push: 'onNavPush'
            },
            cart: {
                pop: 'onCartPop',
                push: 'onCartPush'
            },
            storeList: {
                itemtap: 'onStoreListTap'
            },
            itemList: {
                itemtap: 'onItemListTap'
            },
            countField: {
                spin: 'countChanged'
            },
            orderSubmitBtn: {
                tap: 'orderSubmit'
            },
            cartList: {
                itemtap: 'onCartListTap'
            },
            cartChangeBtn: {
                tap: 'cartChange'
            },
            cartDeleteBtn: {
                tap: 'cartDelete'
            },
            billSubmitBtn: {
                tap: 'billSubmit'
            }
        }
    },
    /**
     * tab 切换,重新加载数据
     * @param panel
     * @param newActiveItem
     * @param oldActiveItem
     * @param eOpts
     */
    tabChange: function (panel, newActiveItem, oldActiveItem, eOpts) {
        console.log(newActiveItem);
        var me = this;
        switch (newActiveItem.xtype) {
            case 'navview':
                console.log('navview');
                me.getCart().pop(me.getCartList());
                Ext.getStore('Store').load();
                break;
            case 'cartnav':
                console.log('cartnav');
                me.getNav().pop(me.getStoreList());
                Ext.getStore('Cart').load();
                break;
        }
        console.log('tabChange');
    },
    /**
     * store 列表点击，显示 item列表
     * @param list
     * @param index
     * @param target
     * @param record
     * @param e
     * @param eOpts
     */
    onStoreListTap: function (list, index, target, record, e, eOpts) {
        console.log('onStoreListTap');
        var me = this;
        var storeId = record.get('id');
        var itemStore = Ext.getStore('Item');
        itemStore.filter('store_id', storeId);
        itemStore.load();
        me.getItemList().set('title', record.get('name'));
        me.getNav().push(me.getItemList());
    },
    /**
     *item 列表点击, 显示order form
     * @param list
     * @param index
     * @param target
     * @param record
     * @param e
     * @param eOpts
     */
    onItemListTap: function (list, index, target, record, e, eOpts) {
        console.log('onItemListTap');
        var me = this;
        var form = me.getOrderForm();
        var storeStore = Ext.getStore('Store');
        console.log(storeStore);
        console.log(record.get('store_id'));
        var store_record = storeStore.getById(record.get('store_id'));
        console.log(store_record);
        form.set('title', store_record.get('name'));
        form.reset();
        form.setRecord(record);
        var item_id = form.down('hiddenfield');
        item_id.setValue(record.get('id'));
        var image = form.down('image');
        image.setSrc(record.get('image'));
        //var priceField = form.down('numberfield[name=price]');
        //priceField.setData({'price': record.get('price')});
        var amountField = form.down('numberfield[name=amount]');
        amountField.setValue(record.get('price'));
        me.getNav().push(form);
    },
    /**
     * cart 列表点击 显示 order form
     * @param list
     * @param index
     * @param target
     * @param record
     * @param e
     * @param eOpts
     */
    onCartListTap: function (list, index, target, record, e, eOpts) {
        console.log('onCartListTap');
        var me = this;
        var form = me.getCartForm();
        form.set('title', record.get('store_name'));
        form.reset();
        form.setRecord(record);
        var image = form.down('image');
        image.setSrc(record.get('image'));
        var amountField = form.down('numberfield[name=amount]');
        amountField.setValue(record.get('price') * record.get('count'));
        me.getCart().push(form);
    },
    /**
     * 导航出栈
     * @param nav
     * @param view
     * @param eOpts
     */
    onNavPop: function (nav, view, eOpts) {
        var me = this;
        console.log(view);
        switch (view.xtype) {
            case 'orderform':
                me.hideOrderSubmitBtn();
                break;
        }
        console.log('onNavPop');
    },
    /**
     * 导航入栈
     * @param nav
     * @param view
     * @param eOpts
     */
    onNavPush: function (nav, view, eOpts) {
        var me = this;
        console.log(view);
        switch (view.xtype) {
            case 'orderform':
                me.showOrderSubmitBtn();
                break;
        }
        console.log('onNavPush');
    },
    /**
     * 导航出栈
     * @param nav
     * @param view
     * @param eOpts
     */
    onCartPop: function (nav, view, eOpts) {
        console.log('onCartPop');
        var me = this;
        switch (view.xtype) {
            case 'orderform':
                me.hideCartChangeBtn();
                break;
        }
    },
    /**
     * 导航入栈
     * @param nav
     * @param view
     * @param eOpts
     */
    onCartPush: function (nav, view, eOpts) {
        console.log('onCartPush');
        var me = this;
        switch (view.xtype) {
            case 'orderform':
                me.showCartChangeBtn();
                break;
        }
    },
    /**
     * 数量变化时计算金额
     * @param field
     * @param value
     * @param direction
     * @param eOpts
     */
    countChanged: function (field, value, direction, eOpts) {
        console.log('countChanged');
        var me = this;
        var form = me.getOrderForm();
        var priceField = form.down('numberfield[name=price]');
        var amountField = form.down('numberfield[name=amount]');
        var price = parseFloat(priceField.getValue());
        var amount = price * value;
        amountField.setValue(amount);
    },
    /**
     * order form 提交
     * @param button
     * @param e
     * @param eOpts
     */
    orderSubmit: function (button, e, eOpts) {
        console.log('orderSubmit');
        var me = this;
        var form = me.getOrderForm();
        var values = form.getValues();
        var item_id = values.item_id;
        var count = values.count;
        console.log(values);
        console.log(item_id);
        console.log(count);
        Ext.Ajax.request({
            method: 'post',
            url: 'api/order',
            params: {
                item_id: item_id,
                count: count
            },
            success: function (response, opts) {
                var text = response.responseText;
                // process server response here
                console.log(text);
                var result = Ext.JSON.decode(text, true);
                if (result.success == true) {
                    // 处理成功
                    Ext.Msg.alert('成功', '所选商品已加入购物车',
                        function () {
                            me.getNav().pop();
                        });
                }
            },
            failure: function (response, opts) {
                console.log('server-side failure with status code ' + response.status);
            }
        });
    },
    /**
     * 显示order 的提交按钮
     */
    showOrderSubmitBtn: function () {
        console.log('showOrderSubmitBtn');
        var me = this;
        var button = me.getOrderSubmitBtn();

        if (!button.isHidden()) {
            return;
        }
        button.show();
    },
    /**
     * 隐藏order 的提交按钮
     */
    hideOrderSubmitBtn: function () {
        console.log('hideOrderSubmitBtn');
        var me = this;
        var button = me.getOrderSubmitBtn();

        if (button.isHidden()) {
            return;
        }
        button.hide();
    },
    /**
     * cart form 的提交按钮
     * @param button
     * @param e
     * @param eOpts
     */
    cartChange: function(button, e, eOpts){
        console.log('cartChange');
        var me = this;
        var form = me.getCartForm();
        var values = form.getValues();
        var item_id = values.item_id;
        var count = values.count;
        console.log(values);
        console.log(item_id);
        console.log(count);
        Ext.Ajax.request({
            method: 'put',
            url: 'api/cart/' + item_id,
            params: {
                //item_id: item_id,
                count: count
            },
            success: function (response, opts) {
                var text = response.responseText;
                // process server response here
                console.log(text);
                var result = Ext.JSON.decode(text, true);
                if (result.success == true) {
                    // 处理成功
                    Ext.Msg.alert('成功', '数量已修改',
                        function () {
                            // 刷新 Cart store
                            Ext.getStore('Cart').load();
                            me.getCart().pop();
                        });
                }
            },
            failure: function (response, opts) {
                console.log('server-side failure with status code ' + response.status);
            }
        });
    },
    /**
     * cart form 的 删除按钮
     * @param button
     * @param e
     * @param eOpts
     */
    cartDelete: function(button, e, eOpts){
        console.log('cartDelete');
        var me = this;
        var form = me.getCartForm();
        var values = form.getValues();
        var item_id = values.item_id;
        console.log(values);
        console.log(item_id);
        Ext.Msg.confirm("确认", "是否要删除所选商品?",
            function(buttonId, value, opt){
                if(buttonId == 'yes'){
                    Ext.Ajax.request({
                        method: 'delete',
                        url: 'api/cart/' + item_id,
                        success: function(response, opts){
                            var text = response.responseText;
                            // process server response here
                            console.log(text);
                            var result = Ext.JSON.decode(text, true);
                            if (result.success == true) {
                                // 处理成功
                                Ext.Msg.alert('成功', '商品已删除',
                                    function () {
                                        // 刷新 Cart store
                                        Ext.getStore('Cart').load();
                                        me.getCart().pop();
                                    });
                            }
                        },
                        failure: function (response, opts) {
                            console.log('server-side failure with status code ' + response.status);
                        }
                    });
                }
            }
        );
    },
    /**
     * 提交最终订单
     * @param button
     * @param e
     * @param eOpts
     */
    billSubmit: function(button, e, eOpts){
        console.log('billSubmit');
        var me = this;
        console.log(me.getCart().getActiveItem());
        var cartStore = Ext.getStore('Cart');
        switch(me.getCart().getActiveItem().xtype){
            case 'cartlist': {
                if(cartStore.getCount() <= 0){
                    Ext.Msg.alert('错误', '购物车为空<br/>请选择商品', function(){
                        me.getMain().setActiveItem(me.getNav());
                    });
                }
                else{
                    var amount = 0;
                    Ext.Array.forEach(cartStore.getData().items,
                        function(item, index, allItems){
                            console.log(item);
                            amount = amount + item.get('price') * item.get('count');
                        }
                    );
                    console.log(amount);
                    var form = me.getBillForm();
                    form.reset();
                    var amountField = form.down('numberfield[name=amount]');
                    amountField.setValue(amount);
                    me.getCart().push(me.getBillForm());
                }
            }
                break;
            case 'cartform': {
                Ext.Array.forEach(cartStore.getData().items,
                    function(item, index, allItems){
                        console.log(item);
                        item.setDirty();
                    }
                );
                console.log(cartStore.getUpdatedRecords());
                var form = me.getBillForm();
                var values = form.getValues();
                console.log(values);
                var model = Ext.ModelMgr.create(values, 'Order.model.CartCheck');
                var errors = model.validate();
                console.log(errors);
                if(errors.isValid()){
                    cartStore.getProxy().setExtraParams(
                        {
                            customer: values.customer,
                            tel: values.tel,
                            comment: values.comment
                        }
                    );
                    cartStore.sync({
                        callback: function (batch, operation) {
                            console.log(batch);
                            console.log(operation);
                            if(!batch.hasException){
                                Ext.Msg.alert('成功', '订单处理成功', function(){
                                    me.getMain().setActiveItem(me.getNav());
                                });
                            }
                            else
                            {
                                Ext.Msg.alert('失败', '订单处理失败', Ext.emptyFn);
                            }
                        }
                    });
                }
                else{
                    var message = '';
                    Ext.Array.forEach(errors.items, function(item, index, allItems){
                            console.log(item);
                            message += item.get('message')+"<br/>";
                        }
                    );
                    Ext.Msg.alert('验证失败', message, Ext.emptyFn);
                }

            }
                break;
        }
    },
    /**
     * 显示cart 的提交按钮和删除按钮
     */
    showCartChangeBtn: function () {
        console.log('showCartChangeBtn');
        var me = this;
        var button = me.getCartChangeBtn();
        if (!button.isHidden()) {
            return;
        }
        button.show();

        button = me.getCartDeleteBtn();
        if (!button.isHidden()) {
            return;
        }
        button.show();

        button = me.getBillSubmitBtn();
        if (button.isHidden()) {
            return;
        }
        button.hide();
    },
    /**
     * 隐藏cart 的提交按钮和删除按钮
     */
    hideCartChangeBtn: function () {
        console.log('hideCartChangeBtn');
        var me = this;
        var button = me.getCartChangeBtn();

        if (button.isHidden()) {
            return;
        }
        button.hide();

        button = me.getCartDeleteBtn();
        if (button.isHidden()) {
            return;
        }
        button.hide();

        button = me.getBillSubmitBtn();
        if (!button.isHidden()) {
            return;
        }
        button.show();
    }
});